package com.easylinkin.linkappapi.common.translate;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.BiConsumer;

import org.springframework.util.ReflectionUtils;

public class CodeTranslateorFactory {

	private static final Map<String, CodeTranslateor> translateors = new HashMap<>(10);

	private CodeTranslateorFactory() {
	}

	/**
	 * 注册翻译器
	 * 
	 * @param clazz
	 * @param tran
	 */
	public static void register(Class<? extends CodeTranslateor> clazz, CodeTranslateor tran) {
		translateors.put(clazz.getName(), tran);
	}

	/**
	 * 进行翻译
	 * 
	 * @param object
	 * @param consumer
	 */
	public static void translate(Object object, BiConsumer<String, String> consumer) {
		if (object == null) {
			return;
		}
		Class<? extends Object> clazz = object.getClass();
		CodeI18n ann = clazz.getAnnotation(CodeI18n.class);
		if (null != ann) {
			List<String> declaredFieldNames = ReflecUtil.getDeclaredFieldNames(clazz, Code2Text.class);
			for (String fieldName : declaredFieldNames) {
				String methodName = ReflecUtil.getMethodName("get", fieldName);
				Method method = ReflectionUtils.findMethod(clazz, methodName);
				if (null != method && ReflecUtil.isGetter(method)) {
					Object getValue = ReflectionUtils.invokeMethod(method, object);
					// 查询对应字段
					Field field = ReflectionUtils.findField(clazz, fieldName);
					String value = "";
					if (null != field && null != getValue) {
						// 注解
						Code2Text code2TextAnn = field.getDeclaredAnnotation(Code2Text.class);
						if (code2TextAnn != null) {
							String key = code2TextAnn.translateorKey();
							if (code2TextAnn.translateor() != null) {
								key = code2TextAnn.translateor().getName();
							}
							CodeTranslateor fieldTranslator = translateors.get(key);
							if (null != fieldTranslator) {
								value = fieldTranslator.translate(clazz, getValue, code2TextAnn);
							}
						}
					}
					consumer.accept(fieldName + "I18n", null == value ? "" : value);
				}
			}
		}
	}

}
